package db

import (
	mydb "FILESTORE-SERVER/db/mysql"
	"fmt"
)

func UserSignup(username, passwd string) bool {
	stmt, err := mydb.DBConn().Prepare(
		"insert ignore into tbl_user (`user_name`, `user_pwd`) values (?,?)")
	if err != nil {
		fmt.Println("Failed to insert , err:" + err.Error())
		return false
	}
	defer stmt.Close()

	// 将参数填入Prepare的sql语句中
	ret, err := stmt.Exec(username, passwd)
	if err != nil {
		fmt.Println("Failed to insert, err:" + err.Error())
		return false
	}

	//判断是否有新的记录插入到数据库中，如果大于0，表示有新数据插入返回true,否则返回false
	rf, err := ret.RowsAffected()
	fmt.Println("rowsaffected : ", rf)
	if nil == err && rf > 0 {
		return true
	}
	return false
}

// 注册的handler
func UserSignin(username, encpwd string) bool {
	stmt, err := mydb.DBConn().Prepare(
		// limit 限制查询结果
		"select * from  tbl_user where user_name = ? limit 1")
	if err != nil {
		fmt.Println(err.Error())
		return false
	}
	defer stmt.Close()
	// 返回查询的行
	rows, err := stmt.Query(username)
	if err != nil {
		fmt.Println(err.Error())
		return false
	} else if rows == nil {
		// 没找到数据
		fmt.Println("username not found: " + username)
		return false
	}
	// 将返回的结果镜像处理
	pRows := mydb.ParseRows(rows)
	if len(pRows) > 0 && string(pRows[0]["user_pwd"].([]byte)) == encpwd {
		return true
	}
	return false
}

// 刷新token
func UpdateToken(username, token string) bool {
	stmt, err := mydb.DBConn().Prepare(
		// replace表示既能插入 又能更新 ，先删除再插入
		"replace into tbl_user_token(`user_name`, `user_token`) values(?,?)")
	if err != nil {
		fmt.Println(err.Error())
		return false
	}
	defer stmt.Close()

	_, err = stmt.Exec(username, token)
	if err != nil {
		fmt.Println(err.Error())
		return false
	}
	return true
}

type User struct {
	Username     string
	Email        string
	Phone        string
	SignupAt     string
	LastActiveAt string
	Status       int
}

func GetUserInfo(username string) (User, error) {
	user := User{}
	stmt, err := mydb.DBConn().Prepare(
		"select user_name, signup_at from tbl_user where user_name = ? limit 1")
	if err != nil {
		fmt.Println(err.Error())
		return user, err
	}
	defer stmt.Close()

	// 执行查询操作
	err = stmt.QueryRow(username).Scan(&user.Username, &user.SignupAt)
	if err != nil {
		return user, nil
	}
	return user, nil
}
